const Sequelize = require("sequelize");

// 创建 Sequelize 实例
const sequelize = new Sequelize("university", "root", "123321", {
  dialect: "mysql",
  host: "localhost",
});


// 定义用户表模型
const User = sequelize.define("user", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  username: {
    type: Sequelize.STRING,
    allowNull: false,
    unique: true,
    primaryKey: true,
  },
  password: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  type: {
    type: Sequelize.INTEGER, //0:普通用户 1:管理员
    allowNull: false,
  },
});




//定义大学表模型
// {
//   "学校名称": "北京大学",
//   "学校标识码": 4111010001,
//   "主管部门": "教育部",
//   "所在地": "北京市",
//   "办学层次": "本科",
//   "location": "116.310918,39.992873"
// }
const Station = sequelize.define("station", {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true,
    autoIncrement: true,
  },
  name: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  //学校标识码
  code: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  //主管部门
  department: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  //所在地
  address: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  //办学层次
  level: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  x: {
    type: Sequelize.STRING,
    allowNull: false,
  },
  y: {
    type: Sequelize.STRING,
    allowNull: false,
  },


});





// 同步模型到数据库
sequelize
  .sync({
    force: false
  })
  .then(async () => {
    console.log("连接成功");
    let u = await Station.findAll();
    if (u.length == 0) {
      User.create({
        username: "admin",
        password: "admin",
        type: 1,
      });

      //读取本地geojson
      const fs = require('fs');
      const path = require('path');
      const filePath = path.join(__dirname, 'station.json');
      const data = fs.readFileSync(filePath);
      const station = JSON.parse(data);
      // "学校名称": "北京大学",
      // "学校标识码": 4111010001,
      // "主管部门": "教育部",
      // "所在地": "北京市",
      // "办学层次": "本科", 
      // "location": "116.310918,39.992873"
      for (let i = 0; i < station.length; i++) {
        let {
          学校名称,
          学校标识码,
          主管部门,
          所在地,
          办学层次,
          location
        } = station[i];
        let [x, y] = location.split(",");
        await Station.create({
          name: 学校名称,
          code: 学校标识码,
          department: 主管部门,
          address: 所在地,
          level: 办学层次,
          x,
          y
        });
      }

    }
  })
  .catch((error) => {
    console.error("失败：", error);
  });

// 导出用户表模型
module.exports = {
  User,
  Station,
  sequelize
}